<template>
    <view class="page">
        <!-- 页面头部 -->
        <view class="page-header">
            <view class="header-title">心动列表</view>
            <view class="header-subtitle">找到让你心动的人</view>
        </view>

        <!-- 搜索区域 -->
        <view class="search-section">
            <view class="search-container">
                <view class="search-input-wrapper">
                    <tui-icon name="search" :size="32" unit="rpx" color="#999" class="search-icon"></tui-icon>
                    <input 
                        class="search-input" 
                        placeholder="搜索姓名或手机号" 
                        placeholder-class="search-placeholder"
                        v-model="inputVal" 
                        @input="handleSearchInput"
                        @confirm="handleSearch"
                        :focus="searchFocus"
                    />
                    <tui-icon 
                        v-if="inputVal" 
                        name="close" 
                        :size="28" 
                        unit="rpx" 
                        color="#999" 
                        class="clear-icon"
                        @tap="clearInput"
                    ></tui-icon>
                </view>
                <view class="search-btn" @tap="handleSearch">
                    <text class="search-btn-text">搜索</text>
                </view>
            </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
            <tui-loading :size="40" unit="rpx" color="#FF6B35"></tui-loading>
            <text class="loading-text">加载中...</text>
        </view>

        <!-- 内容区域 -->
        <scroll-view 
            v-else
            class="content-scroll" 
            scroll-y 
            :scroll-into-view="scrollViewId" 
            :style="{height: winHeight + 'px'}"
        >
            <!-- 有数据时显示列表 -->
            <template v-if="lists.length > 0">
                <!-- 搜索结果 -->
                <view v-if="inputShowed" class="search-results">
                    <view class="result-header">
                        <text class="result-count">找到 {{searchResult.length}} 个结果</text>
                    </view>
                    <view class="user-list">
                        <view 
                            class="user-item" 
                            v-for="(item, index) in searchResult" 
                            :key="index" 
                            @tap="selectUser(item)"
                        >
                            <view class="user-avatar-wrapper">
                                <image 
                                    :src="item.avatar || '/static/img/tabs/my.png'" 
                                    class="user-avatar"
                                    mode="aspectFill"
                                    @error="handleImageError"
                                    @load="handleImageLoad"
                                ></image>
                                <view v-if="item.isOnline" class="online-indicator"></view>
                            </view>
                            <view class="user-info">
                                <view class="user-name-wrapper">
                                    <text class="user-name">{{item.name}}</text>
                                    <view v-if="item.vip" class="vip-badge">VIP</view>
                                </view>
                                <view class="user-details">
                                    <text class="user-career" v-if="item.career">{{item.career}}</text>
                                    <text class="user-degree" v-if="item.degree">{{item.degree}}</text>
                                </view>
                                <view class="user-stats">
                                    <text class="stat-item">评分: {{item.rate || 0}}分</text>
                                    <text class="stat-item">浏览: {{item.pv || 0}}</text>
                                </view>
                                <view class="user-tags" v-if="item.tags && item.tags.length">
                                    <text class="tag" v-for="tag in item.tags" :key="tag">{{tag}}</text>
                                </view>
                            </view>
                            <view class="user-actions">
                                <tui-icon name="arrowright" :size="24" unit="rpx" color="#ccc"></tui-icon>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 分组列表 -->
                <view v-else class="grouped-list">
                    <view v-for="(group, groupIndex) in lists" :key="groupIndex">
                        <template v-if="group.data && group.data.length > 0">
                            <view class="group-header" :id="group.letter">
                                <text class="group-letter">{{group.letter}}</text>
                                <text class="group-count">{{group.data.length}}人</text>
                            </view>
                            <view class="user-list">
                                <view 
                                    class="user-item" 
                                    v-for="(item, itemIndex) in group.data" 
                                    :key="itemIndex" 
                                    @tap="selectUser(item)"
                                >
                                    <view class="user-avatar-wrapper">
                                        <image 
                                            :src="item.avatar || '/static/img/tabs/my.png'" 
                                            class="user-avatar"
                                            mode="aspectFill"
                                            @error="handleImageError"
                                            @load="handleImageLoad"
                                        ></image>
                                        <view v-if="item.isOnline" class="online-indicator"></view>
                                    </view>
                                    <view class="user-info">
                                        <view class="user-name-wrapper">
                                            <text class="user-name">{{item.name}}</text>
                                            <view v-if="item.vip" class="vip-badge">VIP</view>
                                        </view>
                                        <view class="user-details">
                                            <text class="user-career" v-if="item.career">{{item.career}}</text>
                                            <text class="user-degree" v-if="item.degree">{{item.degree}}</text>
                                        </view>
                                        <view class="user-stats">
                                            <text class="stat-item">评分: {{item.rate || 0}}分</text>
                                            <text class="stat-item">浏览: {{item.pv || 0}}</text>
                                        </view>
                                        <view class="user-tags" v-if="item.tags && item.tags.length">
                                            <text class="tag" v-for="tag in item.tags" :key="tag">{{tag}}</text>
                                        </view>
                                    </view>
                                    <view class="user-actions">
                                        <tui-icon name="arrowright" :size="24" unit="rpx" color="#ccc"></tui-icon>
                                    </view>
                                </view>
                            </view>
                        </template>
                    </view>
                </view>
            </template>

            <!-- 无数据时显示空状态 -->
            <view v-else class="empty-container">
                <image src="/static/images/empty-heart.png" class="empty-image" mode="aspectFit"></image>
                <text class="empty-title">暂无心动列表</text>
                <text class="empty-desc">去发现更多有趣的人吧</text>
                <view class="empty-action" @tap="goToDiscover">
                    <text class="action-text">去发现</text>
                </view>
            </view>
        </scroll-view>

        <!-- 右侧字母索引 -->
        <view v-if="!inputShowed && lists.length > 0" class="alphabet-index">
            <view 
                class="index-item" 
                v-for="(group, index) in lists" 
                :key="index"
                @tap="scrollToGroup(group.letter)"
            >
                <text class="index-letter">{{group.letter}}</text>
            </view>
        </view>
    </view>
</template>

<script>
    import empty from "./../components/empty.vue"
    import pingyinUtils from '@/common/lib/util/pingyinUtils.js';
    
    export default {
        data() {
            return {
                lists: [],
                scrollViewId: '', // scroll-view滚动到的子元素的id
                winHeight: 0,
                inputShowed: false, // 输入框是否显示
                inputVal: '', // 搜索框输入的内容
                searchResult: [], // 搜索结果
                loading: false, // 加载状态
                searchFocus: false, // 搜索框焦点状态
                searchTimer: null, // 搜索防抖定时器
                error: null // 错误信息
            };
        },
        components: {
            empty
        },
        onLoad: function (options) {
            this.initPage();
            this.loadData();
        },
        onUnload() {
            // 清理定时器
            if (this.searchTimer) {
                clearTimeout(this.searchTimer);
            }
        },
        methods: {
            // 初始化页面
            initPage() {
                const that = this;
                uni.getSystemInfo({
                    success: function (res) {
                        let winHeight = res.windowHeight;
                        // 减去头部和搜索区域的高度
                        let contentHeight = winHeight - uni.upx2px(200);
                        that.winHeight = contentHeight;
                    }
                });
            },

            // 加载数据
            async loadData() {
                this.loading = true;
                this.error = null;
                
                try {
                    const res = await this.$api.req('/dating/member/relative/page', { 
                        type: 1,
                        pageNo: 1,
                        pageSize: 100
                    }, 'get', 'JSON', false);
                    
                    if (res.code === 0) {
                        const userList = res.data.list || [];
                        this.lists = this.formatData(userList);
                    } else {
                        this.error = res.msg || '加载数据失败';
                        uni.showToast({
                            title: this.error,
                            icon: 'none'
                        });
                    }
                } catch (error) {
                    console.error('加载心动列表失败:', error);
                    this.error = '网络错误，请稍后重试';
                    uni.showToast({
                        title: this.error,
                        icon: 'none'
                    });
                    
                    // 如果网络请求失败，使用测试数据
                    const testData = [
                        {
                            id: 1,
                            userId: 1,
                            name: "测试用户1",
                            cover: "[https://online-miniapp-1304146125.cos.ap-beijing.myqcloud.com/tmp_3b386831ad4bdc994b62babeb96b3315498c5f7d0f9c84bf7934740626697131096.png]",
                            sex: 1,
                            birth: 632332800000,
                            career: "工程师",
                            degree: "本科",
                            vip: 1,
                            rate: 4,
                            pv: 100
                        }
                    ];
                    this.lists = this.formatData(testData);
                } finally {
                    this.loading = false;
                }
            },

            // 格式化数据
            formatData(data) {
                const groupedData = {};
                
                data.forEach(item => {
                    // 获取首字母
                    let firstLetter = item.name ? item.name[0].toUpperCase() : '#';
                    firstLetter = pingyinUtils.chineseToPinYinFirst(firstLetter);
                    
                    if (!groupedData[firstLetter]) {
                        groupedData[firstLetter] = [];
                    }
                    
                    // 处理头像URL
                    let avatarUrl = '/static/img/tabs/my.png';
                    
                    if (item.cover && typeof item.cover === 'string') {
                        try {
                            // 先去掉首尾的方括号，然后解析JSON
                            let coverStr = item.cover.trim();
                            
                            // 如果首尾是方括号，去掉它们
                            if (coverStr.startsWith('[') && coverStr.endsWith(']')) {
                                coverStr = coverStr.slice(1, -1);
                            }
                            
                            // 现在解析JSON数组
                            const coverArray = JSON.parse('[' + coverStr + ']');
                            
                            // 检查是否为数组且有数据
                            if (Array.isArray(coverArray) && coverArray.length > 0) {
                                avatarUrl = coverArray[0];
                            }
                        } catch (e) {
                            // 如果JSON解析失败，尝试直接提取URL
                            const urlMatch = item.cover.match(/https?:\/\/[^\]]+/);
                            if (urlMatch) {
                                avatarUrl = urlMatch[0];
                            }
                        }
                    }
                    
                    groupedData[firstLetter].push({
                        id: item.id,
                        userId: item.userId,
                        name: item.name || '未知用户',
                        mobile: item.mobile || '',
                        avatar: avatarUrl,
                        keyword: (item.name || '').toUpperCase() + (item.mobile || ''),
                        isOnline: Math.random() > 0.5, // 模拟在线状态
                        tags: this.generateUserTags(item), // 生成用户标签
                        vip: item.vip,
                        score: item.score,
                        rate: item.rate,
                        pv: item.pv,
                        recommendCount: item.recommendCount,
                        wishCount: item.wishCount,
                        collectCount: item.collectCount,
                        career: item.career,
                        degree: item.degree,
                        sex: item.sex,
                        birth: item.birth,
                        ...item // 保留其他原始数据
                    });
                });
                
                // 转化为数组并排序
                return Object.keys(groupedData)
                    .sort()
                    .map(letter => ({
                        letter,
                        data: groupedData[letter]
                    }));
            },

            // 生成用户标签
            generateUserTags(user) {
                const tags = [];
                
                // 根据出生日期计算年龄
                if (user.birth) {
                    const birthDate = new Date(user.birth);
                    const now = new Date();
                    const age = now.getFullYear() - birthDate.getFullYear();
                    if (age > 0 && age < 100) {
                        tags.push(`${age}岁`);
                    }
                }
                
                // 职业
                if (user.career) {
                    tags.push(user.career);
                }
                
                // 学历
                if (user.degree) {
                    tags.push(user.degree);
                }
                
                // VIP状态
                if (user.vip) {
                    tags.push('VIP');
                }
                
                // 性别
                if (user.sex) {
                    tags.push(user.sex === 1 ? '男' : '女');
                }
                
                return tags.slice(0, 3); // 最多显示3个标签
            },

            // 格式化手机号
            formatMobile(mobile) {
                if (!mobile) return '';
                if (mobile.length === 11) {
                    return mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
                }
                return mobile;
            },

            // 搜索输入处理（防抖）
            handleSearchInput(e) {
                this.inputVal = e.detail.value;
                
                // 清除之前的定时器
                if (this.searchTimer) {
                    clearTimeout(this.searchTimer);
                }
                
                // 设置防抖
                this.searchTimer = setTimeout(() => {
                    this.performSearch();
                }, 300);
            },

            // 执行搜索
            performSearch() {
                if (!this.inputVal.trim()) {
                    this.inputShowed = false;
                    this.searchResult = [];
                    return;
                }
                
                const keyword = this.inputVal.trim().toUpperCase();
                const result = [];
                
                this.lists.forEach(group => {
                    group.data.forEach(user => {
                        if (user.keyword.includes(keyword)) {
                            result.push(user);
                        }
                    });
                });
                
                this.inputShowed = true;
                this.searchResult = result;
            },

            // 搜索按钮点击
            handleSearch() {
                this.performSearch();
            },

            // 清空搜索
            clearInput() {
                this.inputVal = '';
                this.inputShowed = false;
                this.searchResult = [];
                this.searchFocus = false;
            },

            // 选择用户
            selectUser(user) {
                console.log('选择用户:', user);
                // 跳转到用户详情页
                uni.navigateTo({
                    url: `/subPackage1/marriageDetail/marriageDetail?id=${user.userId}`
                });
            },

            // 滚动到指定分组
            scrollToGroup(letter) {
                this.scrollViewId = letter;
                setTimeout(() => {
                    this.scrollViewId = '';
                }, 1000);
            },

            // 去发现页面
            goToDiscover() {
                uni.switchTab({
                    url: '/pages/index/index'
                });
            },

            // 图片加载成功
            handleImageLoad(e) {
                // 图片加载成功
            },

            // 图片加载失败
            handleImageError(e) {
                // 图片加载失败，可以在这里设置默认头像
            }
        }
    };
</script>




<style lang="scss" scoped>
    page {
        height: 100%;
        background: #f8f9fa;
    }

    .page {
        height: 100%;
        display: flex;
        flex-direction: column;
        background: #f8f9fa;
    }

    /* 页面头部 */
    .page-header {
        background: linear-gradient(135deg, #a55fee, #c77dff);
        padding: 40rpx 30rpx 30rpx;
        color: white;
    }

    .header-title {
        font-size: 36rpx;
        font-weight: 600;
        margin-bottom: 8rpx;
    }

    .header-subtitle {
        font-size: 26rpx;
        opacity: 0.9;
    }

    /* 搜索区域 */
    .search-section {
        background: white;
        padding: 20rpx 30rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    .search-container {
        display: flex;
        align-items: center;
        gap: 20rpx;
    }

    .search-input-wrapper {
        flex: 1;
        position: relative;
        background: #f5f5f5;
        border-radius: 25rpx;
        padding: 0 20rpx;
        height: 70rpx;
        display: flex;
        align-items: center;
    }

    .search-icon {
        margin-right: 15rpx;
    }

    .search-input {
        flex: 1;
        height: 100%;
        font-size: 28rpx;
        color: #333;
        background: transparent;
        border: none;
        outline: none;
    }

    .search-placeholder {
        color: #999;
        font-size: 28rpx;
    }

    .clear-icon {
        margin-left: 15rpx;
        padding: 10rpx;
    }

    .search-btn {
        background: #a55fee;
        border-radius: 25rpx;
        padding: 0 30rpx;
        height: 70rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 120rpx;
    }

    .search-btn-text {
        color: white;
        font-size: 28rpx;
        font-weight: 500;
    }

    /* 加载状态 */
    .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 100rpx 0;
    }

    .loading-text {
        margin-top: 20rpx;
        font-size: 28rpx;
        color: #666;
    }

    /* 内容滚动区域 */
    .content-scroll {
        flex: 1;
        background: #f8f9fa;
    }

    /* 搜索结果 */
    .search-results {
        background: white;
        margin: 20rpx;
        border-radius: 16rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    .result-header {
        padding: 20rpx 30rpx;
        background: #f8f9fa;
        border-bottom: 1rpx solid #eee;
    }

    .result-count {
        font-size: 26rpx;
        color: #666;
    }

    /* 分组列表 */
    .grouped-list {
        padding: 0 20rpx;
    }

    .group-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 30rpx;
        background: #f8f9fa;
        margin: 20rpx 0 10rpx;
        border-radius: 12rpx;
        box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
    }

    .group-letter {
        font-size: 32rpx;
        font-weight: 600;
        color: #a55fee;
    }

    .group-count {
        font-size: 24rpx;
        color: #999;
    }

    /* 用户列表 */
    .user-list {
        background: white;
        border-radius: 16rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        margin-bottom: 20rpx;
    }

    .user-item {
        display: flex;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #f0f0f0;
        transition: background-color 0.2s;
    }

    .user-item:last-child {
        border-bottom: none;
    }

    .user-item:active {
        background-color: #f8f9fa;
    }

    .user-avatar-wrapper {
        position: relative;
        margin-right: 24rpx;
    }

    .user-avatar {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        border: 3rpx solid #f0f0f0;
    }

    .online-indicator {
        position: absolute;
        bottom: 5rpx;
        right: 5rpx;
        width: 20rpx;
        height: 20rpx;
        background: #4CAF50;
        border-radius: 50%;
        border: 3rpx solid white;
    }

    .user-info {
        flex: 1;
        min-width: 0;
    }

    .user-name-wrapper {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
    }

    .user-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 12rpx;
    }

    .vip-badge {
        background: linear-gradient(135deg, #ffd700, #ffed4e);
        color: #8b4513;
        font-size: 18rpx;
        font-weight: 600;
        padding: 2rpx 8rpx;
        border-radius: 8rpx;
        text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
    }

    .user-details {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
        gap: 16rpx;
    }

    .user-career {
        font-size: 24rpx;
        color: #666;
        background: #f0f0f0;
        padding: 2rpx 8rpx;
        border-radius: 6rpx;
    }

    .user-degree {
        font-size: 24rpx;
        color: #666;
        background: #e8f4fd;
        padding: 2rpx 8rpx;
        border-radius: 6rpx;
    }

    .user-stats {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;
        gap: 20rpx;
    }

    .stat-item {
        font-size: 22rpx;
        color: #999;
    }

    .user-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8rpx;
    }

    .tag {
        background: #a55fee;
        color: white;
        font-size: 20rpx;
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
    }

    .user-actions {
        margin-left: 20rpx;
    }

    /* 空状态 */
    .empty-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 120rpx 60rpx;
        text-align: center;
    }

    .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 40rpx;
    }

    .empty-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 16rpx;
    }

    .empty-desc {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 40rpx;
        line-height: 1.5;
    }

    .empty-action {
        background: #a55fee;
        color: white;
        padding: 20rpx 40rpx;
        border-radius: 25rpx;
        font-size: 28rpx;
        font-weight: 500;
    }

    .action-text {
        color: white;
    }

    /* 字母索引 */
    .alphabet-index {
        position: fixed;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        z-index: 100;
        display: flex;
        flex-direction: column;
        gap: 4rpx;
    }

    .index-item {
        width: 40rpx;
        height: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.9);
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        transition: all 0.2s;
    }

    .index-item:active {
        background: #a55fee;
        transform: scale(1.1);
    }

    .index-letter {
        font-size: 22rpx;
        color: #666;
        font-weight: 500;
    }

    .index-item:active .index-letter {
        color: white;
    }

    /* 响应式适配 */
    @media screen and (max-width: 750rpx) {
        .user-avatar {
            width: 80rpx;
            height: 80rpx;
        }
        
        .user-name {
            font-size: 30rpx;
        }
        
        .user-mobile {
            font-size: 24rpx;
        }
    }
</style>